package 集合相关.queue;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class BlockingQueueTest {
	/**
	 * 实例化一个队列，队列中的容量为10
	 */
	private static BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<>(
			10);

	public static void main(String[] args) {
		ScheduledExecutorService product = Executors.newScheduledThreadPool(1);
		final Random random = new Random();
		product.scheduleAtFixedRate(new Runnable() {

			@Override
			public void run() {
				int value = random.nextInt(101);
				try {
					blockingQueue.offer(value); // offer()方法就是网队列的尾部设置值
					System.out.println("设置的value=" + value);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}, 0, 1, TimeUnit.SECONDS);

		new Thread(new Runnable() {

			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(3000);
						System.out.println("开始取值");
						List<Integer> list = new LinkedList<>();
						blockingQueue.drainTo(list); // drainTo()将队列中的值全部从队列中移除，并赋值给对应集合
						for (int i = 0; i < list.size(); i++) {
							System.out.println(list.get(i));
						}
						System.out.println("取值结束");
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

			}
		}).start();
		;

	}
}